package com.zzg.cloud.feignresponse;

import feign.Response;
import lombok.SneakyThrows;
import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;

@RestController
@RequestMapping("/feignResponse")
public class FeignResponseController {
    @Resource
    private TransferLogFeignApi transferLogFeignApi;

    @PostMapping("/exportTransferLogUrl")
    public void exportTransferLogUrl(@RequestBody PoolTransferLogReq poolTransferLogReq, HttpServletResponse response){
        Response feignResponse = transferLogFeignApi.exportTransferLog(poolTransferLogReq);
        feignResp2ServletResp(feignResponse, response);
    }

    /**
     * Feign的Response转化成HttpServletResponse
     * @param
     * @return
     */
    @SneakyThrows
    public void feignResp2ServletResp(Response feignResponse, HttpServletResponse response) {
        Response.Body body = feignResponse.body();
        try (InputStream inputStream = body.asInputStream(); OutputStream outputStream = response.getOutputStream()) {
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, feignResponse.headers().get(HttpHeaders.CONTENT_DISPOSITION).stream().findFirst().get());
            response.setContentType(feignResponse.headers().get(HttpHeaders.CONTENT_TYPE).stream().findFirst().get());
            IOUtils.copy(inputStream, outputStream);
        }
    }
}
